
import { mineApi } from "@/utils/request/api/mine";
import { publicApi } from "@/utils/request/api/public";
import Toast from '@vant/weapp/toast/toast';
const {imgUrl} = getApp().globalData
Page({
  data: {
    showPop: 0,
    imgUrl: imgUrl + 'mine/',
    isPhone: false,
    phoneTimer: null,
    phoneTime: 60,
    emailTimer: null,
    emailTime: 60,
    isLoading: false,
    showSelectIndustry: false,
    showSelectCity: false,
    industryList: [],
    citys: [],
    city_columns: [],
    // 个人信息
    myInfo: {
      id: -1, //id为0是新增，不为0是修改
      user_type: 1, //用户类型，1-普通用户，2-企业用户
      mobile: "", //手机号码
      email: "", //电子邮箱，比如 example@qq.com
      password: "", //密码
      user_no: "", //账户ID号
      real_name: "", //真名
      nick_name: "", //昵称
      avatar: "", //头像
      is_cancel: false, //是否注销
      is_expert: false, //是否认证为专家
      is_course_note: false, //是否课程笔记禁言
      is_course_comment: false, //是否课程评论禁言
      address: "", //地区
      industry: "", //行业
      signature: "", //签名
      status: true, //用户账号状态	0：禁用	1：正常
      note: "",
      open_id: "", //微信用户唯一标识
      followers_count: 1, //粉丝数量
      following_count: 1, //关注数量
      likes_count: 0, //获赞数量
      created_ip: "",
      coin_balance: 100, //金币余额
      coin_expense: 0, //金币支出总额
      vip_type: 0, //vip类型，1-周卡，2-月卡，3-季度卡，4-年卡，5-超级会员
      vip_expire_time: 0, //vip到期时间，unix秒数
      created_at: "",
      updated_at: "",
    },
    reSetPhone: {
      newPhone: "",
      code: ""
    },
    reSetInfo: {
      signature: "", //签名
      nick_name: "", //昵称
      avatar: "", //头像
      address: "", //地区
      industry: "", //行业
    },
    origin: {
      signature: "", //签名
      nick_name: "", //昵称
      avatar: "", //头像
      address: "", //地区
      industry: "", //行业
    }
  },
  onChange(event) {
    let key = event.currentTarget.dataset.keyword;
    let val = event.detail;
    let obj = JSON.parse(JSON.stringify(this.data.reSetPhone));
    obj[key] = val;
    this.setData({
      reSetPhone: obj
    })
    if (key === 'newPhone') {
      if (/^1[3456789]\d{9}$/.test(val)) {
        this.setData({
          isPhone: true
        })
      } else {
        this.setData({
          isPhone: false
        })
      }
    }
  },
  onChange2(event) {
    let key = event.currentTarget.dataset.keyword;
    let val = event.detail;
    let obj = JSON.parse(JSON.stringify(this.data.origin));
    obj[key] = val.value || val;
    this.setData({
      origin: obj
    })
  },
  changePop(event) {
    let n = event.currentTarget.dataset.index;
    this.setData({
      showPop: n
    })
  },
  showSelector(event) {
    const index = event.currentTarget.dataset.index;
    if (index == 1) {
      this.setData({
        showSelectIndustry: true
      })
    } else if (index == 2) {
      this.setData({
        showSelectCity: true
      })
    }
  },
  closePop() {
    let obj = JSON.parse(JSON.stringify(this.data.origin));
    if (this.data.showPop == 2) {
      obj.signature = this.data.reSetInfo.signature;
    } else if (this.data.showPop == 3) {
      obj.nick_name = this.data.reSetInfo.nick_name;
    }
    this.setData({
      showPop: 0,
      origin: obj
    })
  },
  // 获取手机验证码
  getPhoneCode() {
    if (!this.data.reSetPhone.newPhone || !this.data.isPhone) {
      Toast.fail('请输入正确的手机号！');
      return
    }
    if (this.data.phoneTimer) {
      return
    }
    this.setData({
      phoneTime: 60
    }, () => {
      this.data.phoneTimer = setInterval(() => {
        let n = this.data.phoneTime - 1;
        this.setData({
          phoneTime: n
        }, () => {
          if (n === 0) {
            clearInterval(this.data.phoneTimer)
            this.data.phoneTimer = null;
            this.setData({
              phoneTime: 60
            })
          }
        })
      }, 1000)
    })
    publicApi.getPhoneCode({
      mobile: this.data.reSetPhone.newPhone
    }).then(res => {
      Toast.success('验证码发送成功，请查收！');
    }).catch(err => {
      console.log('err === ', err)
      Toast.fail('验证码获取失败，请稍后再试！');
    })
  },
  // 提交新的手机
  changeNewPhone() {
    if (!this.data.reSetPhone.newPhone ||!this.data.isPhone) {
      Toast.fail('请输入正确的手机号！');
      return
    }
    if (!this.data.reSetPhone.code) {
      Toast.fail('请输入验证码！');
      return
    }
    this.setData({
      isLoading: true
    })
    let obj = {
      id: 1,
      new_mobile: this.data.reSetPhone.newPhone,
      sms_code: this.data.reSetPhone.code
    };
    mineApi.changePhone(obj).then(res => {
      Toast.success('提交成功！');
      this.setData({
        showPop: 0,
        isLoading: false
      })
    }).catch(err => {
      console.log('err === ', err)
      Toast.fail('验证码获取失败，请稍后再试！');
    })
  },
  confirmEdit(event) {
    this.setData({
      reSetInfo: this.data.origin,
      showPop: 0
    })
  },
  toRz() {
    if (this.data.myInfo.is_expert) {
      wx.navigateTo({
        url: "/pages/mine/authoritied/authoritied"
      })
    } else {
      wx.navigateTo({
        url: "/pages/mine/authority/authority"
      })
    }
  },
  // 选择行业
  cancelindustry() {
    this.setData({
      showSelectIndustry: false
    })
  },
  confirmindustry(event) {
    const { picker, value, index } = event.detail;
    const obj = JSON.parse(JSON.stringify(this.data.origin));
    obj.industry = this.data.industryList[index];
    this.setData({
      origin: obj,
      reSetInfo: obj,
      showSelectIndustry: false
    })
  },
  // 选择城市
  cancelcity() {
    this.setData({
      showSelectCity: false
    })
  },
  confirmcity(event) {
    console.log(1)
    const { picker, value, index } = event.detail;
    const obj = JSON.parse(JSON.stringify(this.data.origin));
    console.log('val === ', value)
    obj.address = value.join('-')
    this.setData({
      origin: obj,
      reSetInfo: obj,
      showSelectCity: false
    })
  },
  changeCity(event) {
    const { picker, value, index } = event.detail;
    picker.setColumnValues(1, this.data.citys[value[0]]);
  },
  chooseImage(event) {
    const that = this;
    wx.chooseMessageFile({
      count: 1,
      type: "file",
      extension: ["jpg", "png", "jpeg"],
      success: function (res) {
        const filePath = res.tempFiles[0].path;
        const formData = {
          fileVal: filePath,
          name: res.tempFiles[0].name,
        };

        publicApi
          .uploadFile({
            filePath,
            formData,
          })
          .then((res) => {
            let obj = JSON.parse(JSON.stringify(that.data.reSetInfo))
            obj.avatar = res.data 
            that.setData({
              reSetInfo: obj,
              origin: obj
            })
          });
      },
    });
  },
  saveInfo() {
    let obj = {}
    if (this.data.reSetInfo.signature != this.data.myInfo.signature) {
      obj.signature = this.data.reSetInfo.signature
    }
    if (this.data.reSetInfo.nick_name!= this.data.myInfo.nick_name) {
      obj.nick_name = this.data.reSetInfo.nick_name
    }
    if (this.data.reSetInfo.avatar!= this.data.myInfo.avatar) {
      obj.avatar = this.data.reSetInfo.avatar
    }
    if (this.data.reSetInfo.address!= this.data.myInfo.address) {
      obj.address = this.data.reSetInfo.address
    }
    if (this.data.reSetInfo.industry!= this.data.myInfo.industry) {
      obj.industry = this.data.reSetInfo.industry
    }
    if (JSON.stringify(obj) == '{}') {
      Toast.fail('请修改信息！');
      return
    }
    obj.id = this.data.myInfo.id;
    mineApi.editMineUserInfo(obj).then(res => {
      console.log('person res === ', res)
      Toast.success('修改个人信息成功！');
    })
  },
  onLoad(options) {
    mineApi
      .getMineUserInfo()
      .then((res) => {
        if (res.data) {
          let obj = res.data;
          obj.created_at = obj.created_at.split(' ')[0]
          this.setData({
            myInfo: obj,
            reSetInfo: {
              id: obj.id,
              signature: obj.signature, //签名
              nick_name: obj.nick_name, //昵称
              avatar: obj.avatar, //头像
              address: obj.address, //地区
              industry: obj.industry, //行业
            },
            origin: {
              id: obj.id,
              signature: obj.signature, //签名
              nick_name: obj.nick_name, //昵称
              avatar: obj.avatar, //头像
              address: obj.address, //地区
              industry: obj.industry, //行业
            }
          });
        }
      }).catch((err) => {
        console.log('err === ', err);
      });

    publicApi.getIndustryList().then(res => {
      this.setData({
        industryList: res.data.map(item => item.name) || []
      })
    })

    publicApi.getAreaList().then(res => {
      let sheng = res.rows.filter(item => item.level === 1)
      let citys = {}
      sheng.forEach(item => {
        citys[item.name] = res.rows.filter(item2 => item2.pcode === item.code).map(item3 => item3.name)
      })
      console.log('ccc === ', citys)
      let cs = [
        {
          values: Object.keys(citys),
          className: 'column1',
        }, {
          values: citys['北京市'],
          className: 'column2',
          defaultIndex: 2,
        }
      ]
      this.setData({
        citys,
        city_columns: cs
      })
    })
  },
  onReady() {
  },
  onShow() {
  },
  onHide() {
  },
  onUnload() {
  },
  onShareAppMessage() {
    return {
      title: '',
    };
  },
});